package com.wh.wisdomsite.xbox.server.controller.ba;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.wh.wisdomsite.xbox.ba.entity.CommonFile;
import com.wh.wisdomsite.xbox.ba.service.ICommonFileService;
import com.wh.wisdomsite.xbox.ba.service.IFileService;
import com.wh.wisdomsite.xbox.common.util.ResManager;
import com.wh.wisdomsite.xbox.pojo.ba.CommonFileIn;
import com.wh.wisdomsite.xbox.server.manager.UserMapManager;
import com.wh.wisdomsite.xbox.server.session.ServerSessionUser;
import com.wh.wisdomsite.xbox.server.util.UserUtils;
import com.wh.wisdomsite.xbox.utils.StringUtils;
import com.wh.wisdomsite.xbox.utils.date.DateTool;
import com.wh.wisdomsite.xbox.utils.file.FileTool;
import com.wh.wisdomsite.xbox.utils.json.JsonUtil;
import com.wh.wisdomsite.xbox.utils.json.JsonUtil_Org;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * 公共附件存储controller
 * @author 刘旭
 * @version V1.0
 * @Package com.wh.wisdomsite.xbox.server.controller.ba
 * @date 2018年08月19日 20:58
 * @Copyright 企业版权所有
 * @Company 贵州万华科技有限公司Copyright (c) 2018
 */
@Controller
@RequestMapping(value = "/commonFile")
public class CommonFileController {
    private static final Log logger = LogFactory.getLog(CommonFileController.class);
    @Autowired
    private ICommonFileService iCommonFileService;

    @Autowired
    private IFileService iFileService;

    /**
     * 跳转到公共附件页面
     *
     * @return
     */
    @RequiresPermissions("rules:ba_commonFile_page")
    @RequestMapping(value = "/index.do", method = RequestMethod.GET)
    public String index() {
        return "ba/commonFile/commonFileList";
    }

    /**
     * 获取公共附件列表
     *
     * @param response
     * @param in
     */
    @RequiresPermissions("rules:ba_commonFile_find")
    @RequestMapping(value = "/commonFileList.do")
    public void commonFileList(HttpServletResponse response, CommonFileIn in) {
        try {
            logger.info("加载公共附件列表-->>开始");
            if (in.getPage() == 0) in.setPage(1);
            if (in.getRows() == 0) in.setRows(10);
            Page<CommonFile> page = new Page<CommonFile>();
            page.setCurrent(in.getPage());
            page.setSize(in.getRows());
            //设置条件
            EntityWrapper<CommonFile> ewCommonFile = new EntityWrapper<CommonFile>();
            ewCommonFile.setEntity(new CommonFile());
            if (StringUtils.isNotEmpty(in.getModelCode())) {
                ewCommonFile.eq("modelCode", in.getModelCode());
            }

            if (StringUtils.isNotEmpty(in.getFunCode())) {
                ewCommonFile.eq("funCode", in.getFunCode());
            }
            if (StringUtils.isNotEmpty(in.getName())) {
                ewCommonFile.like("name", in.getName());
            }
            if (StringUtils.isNotEmpty(in.getCreateId())) {
                ewCommonFile.eq("createBy", in.getCreateId());
            }
            //若用户不是超级管理员根据用户的数据权限添加查询条件
            if(!UserUtils.isSysAdmin()){
                ewCommonFile = setEntityWrapper(ewCommonFile);
            }
            ewCommonFile.orderBy("createDate", false);
            Page<CommonFile> commonFilePage = iCommonFileService.selectPage(page, ewCommonFile);
            JSONObject json = new JSONObject();
            JSONArray array = new JSONArray();
            if (commonFilePage.getRecords().size() > 0) {
                for (CommonFile commonFile : commonFilePage.getRecords()) {
                    JSONObject object = new JSONObject(commonFile);
                    object.put("createdate", DateTool.format(commonFile.getCreatedate(), "yyyy-MM-dd hh:mm:ss"));
                    array.put(object);
                }
            }
            json.put("total", commonFilePage.getTotal());
            json.put("rows", array);
            ResManager.getJsonOut(response).print(json);
            logger.info("加载公共附件列表-->>结束");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 公共附件详情
     * @param id
     * @param request
     * @return
     */
    @RequiresPermissions("rules:ba_commonFile_view")
    @RequestMapping("commonFileDesc.do")
    public String commonFileDesc(String id, HttpServletRequest request) {
        logger.info("公共附件详情-->>开始");
        CommonFile commonFile = iCommonFileService.selectById(id);
        if(null != commonFile.getCreateby()){
            commonFile.setCreateby( UserMapManager.getUserLoginNameInMap(commonFile.getCreateby()));
        }
        request.setAttribute("commonFile", commonFile);
        String fileSize = commonFile.getSize();
        String fileSizeFormat = FileTool.getPrintSize(Long.parseLong(fileSize));
        commonFile.setSize(fileSizeFormat);
        request.setAttribute("creatDate", DateTool.format(commonFile.getCreatedate(), "yyyy-MM-dd HH:mm:ss"));
        logger.info("公共附件详情-->>结束");
        return "ba/commonFile/commonFileDesc";
    }

    /**
     * 删除公共附件
     * @param id
     * @param response
     */
    @RequiresPermissions("rules:ba_commonFile_del")
    @RequestMapping(value = "delCommonFile.do", method = RequestMethod.GET)
    public void delCommonFile(String id, HttpServletResponse response) {
        try {
            logger.info("删除公共附件-->>开始");
            iCommonFileService.deleteById(id);
            logger.info("删除公共附件-->>结束");
            ResManager.getJsonOut(response).print(JsonUtil_Org.returnTrue("删除成功"));
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("删除公共附件-->>Exception" + e.getMessage());
        }
    }

    /**
     * 根据fileId获取可用的url
     * @param id
     * @param response
     */
    @RequestMapping(value = "getFileUrlById.do", method = RequestMethod.GET)
    public void getFileUrlById(String id, HttpServletResponse response) {
        try {
            logger.info("获取附件URL-->>开始");
            String url = iFileService.getUrlById(id);
            logger.info("获取附件URL-->>结束");
            ResManager.getJsonOut(response).print(JsonUtil_Org.returnTrue(url));
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("获取附件URL-->>Exception" + e.getMessage());
        }
    }

    /**
     * 获取所有功能模块
     * @param response
     */
    @RequestMapping(value = "/getModelList.do")
    public void getModelList(HttpServletResponse response) {
        List<CommonFile> commonFile = new ArrayList<CommonFile>();
        try {
            logger.info("获取所有模块-->>开始");
            EntityWrapper<CommonFile> ewCommonFile = new EntityWrapper<CommonFile>();
            ewCommonFile.setEntity(new CommonFile());
            //若用户不是超级管理员根据用户的数据权限添加查询条件
            if(!UserUtils.isSysAdmin()){
                ewCommonFile = setEntityWrapper(ewCommonFile);
            }
            ewCommonFile.groupBy("modelName");
            commonFile = iCommonFileService.selectList(ewCommonFile);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("获取所有模块-->>异常Exception " + e.getMessage());
        }
        ResManager.getJsonOut(response).print(JsonUtil.Json2All(commonFile));
        logger.info("获取所有模块-->>结束");
    }

    /**
     * 根据模块代码获取所有功能模块
     *
     * @param response
     */
    @RequestMapping(value = "/getFunList.do")
    public void getFunList(HttpServletResponse response, String modelCode) {
        List<CommonFile> commonFile = new ArrayList<CommonFile>();
        try {
            logger.info("获取所有功能模块-->>开始");
            EntityWrapper<CommonFile> ewCommonFile = new EntityWrapper<CommonFile>();
            ewCommonFile.setEntity(new CommonFile());
            ewCommonFile.eq("modelCode", modelCode);
            ewCommonFile.groupBy("funCode");
            commonFile = iCommonFileService.selectList(ewCommonFile);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("获取所有功能模块-->>异常Exception " + e.getMessage());
        }
        ResManager.getJsonOut(response).print(JsonUtil.Json2All(commonFile));
        logger.info("获取所有功能模块-->>结束");
    }

    /**
     * 获取创建的用户
     * @param response
     */
    @RequestMapping(value = "/getUserList.do")
    public void getUserList(HttpServletResponse response) {
        JSONArray jsonArray = new JSONArray();
        try {
            List<CommonFile> commonFileList = new ArrayList<CommonFile>();
            logger.info("获取所有功能模块-->>开始");
            EntityWrapper<CommonFile> ewCommonFile = new EntityWrapper<CommonFile>();
            ewCommonFile.setEntity(new CommonFile());
            //若用户不是超级管理员根据用户的数据权限添加查询条件
            if(!UserUtils.isSysAdmin()){
                ewCommonFile = setEntityWrapper(ewCommonFile);
            }
            ewCommonFile.groupBy("createBy");
            commonFileList = iCommonFileService.selectList(ewCommonFile);
            for(CommonFile commonFile : commonFileList){
                String createId = commonFile.getCreateby();
                String createName = UserMapManager.getUserLoginNameInMap(createId);
                JSONObject obj = new JSONObject();
                obj.put("userId",createId);
                obj.put("userName",createName);
                jsonArray.put(obj);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("获取所有功能模块-->>异常Exception " + e.getMessage());
        }
        ResManager.getJsonOut(response).print(jsonArray);
        logger.info("获取所有功能模块-->>结束");
    }

    /**
     * 根据权限设置查询范围
     * @param ew
     * @return
     */
    public EntityWrapper setEntityWrapper(EntityWrapper ew) {
        ServerSessionUser serverSessionUser = UserUtils.getServerSessionUser();
        String dataScope = serverSessionUser.getDataScope();
        //设置一个查询用的代码
        String codeForFind = null;
        switch (dataScope) {
            case "1":
                codeForFind = serverSessionUser.getFinalCompCode();
                if(org.apache.commons.lang3.StringUtils.isNotEmpty(codeForFind)){
                    ew.like("compCode", codeForFind);
                }
                break;
            case "2":
                codeForFind = serverSessionUser.getFinalCompCode();
                if(org.apache.commons.lang3.StringUtils.isNotEmpty(codeForFind)){
                    ew.eq("compCode", codeForFind);
                }
                break;
            case "3":
                codeForFind = serverSessionUser.getFinalCompCode();
                if(org.apache.commons.lang3.StringUtils.isNotEmpty(codeForFind)){
                    ew.eq("compCode", codeForFind);
                }
                break;
            case "4":
                codeForFind = serverSessionUser.getFinalCompCode();
                if(org.apache.commons.lang3.StringUtils.isNotEmpty(codeForFind)){
                    ew.eq("compCode", codeForFind);
                }
                break;
            case "5":
                codeForFind = serverSessionUser.getFinalCompCode();
                if(org.apache.commons.lang3.StringUtils.isNotEmpty(codeForFind)){
                    ew.eq("compCode", codeForFind);
                }
                break;
            default:break;
        }
        return ew;
    }

}
